#!/bin/bash
#name=`basename $0`
##//设置脚本中所需命令的执行路径
export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin"
##// $? 是取得上面执行命令的返回值，一般正确为0，错误为1
if [ "$?" != 0 ] ;
then
 ##//echo 为输出到屏幕
 echo "Please check your need software"
 ##//exit 0 为强制终止脚本
 exit 0
fi
cd `dirname $0`
##//name执行的脚本文件的全名
name=$(basename $0)
##/PGNAME包名通过脚本名获取，需要包名与脚本名一直
PGNAME=${name%.sh*}
##//SERVERVERSION安装包版本信息
VERSION=${PGNAME##*V}
SERVERVERSION=
##//HOMEPATH安装目录 /usr/local/tomcat
HOMEPATH=/usr/CommandCenter
##//SERVERPORT服务端口
SERVERPORT=22401
##//SERVERNAME服务名称
SERVERNAME=CDSS
##//SERVERDIR服务所在文件目录 安装目录（HOMEPATH）下级目录
SERVERDIR=CDSS
##//docker镜像名
DOCKERNAME=cdss
##//docker容器名
CONTAINERNAME=CDSS
##//宿主机需要开放的端口
OPENPORT="22401"

OPTSTATUS=200
PGIP=0.0.0.0
PGPORT=5432
PGUSER=postgres
PGPWD=123456
while getopts ":i:v:p:u:w:s:" opt
do
    case $opt in
        i)
        echo "ip--$OPTARG"
	PGIP=$OPTARG;
        ;;
	    v)
        echo "version--$OPTARG"
    SERVERVERSION=V$OPTARG;
        ;;
        p)
        echo "port--$OPTARG"
	PGPORT=$OPTARG;
        ;;
        u)
        echo "user--$OPTARG"
	PGUSER=$OPTARG;
        ;;
        w)
        echo "pwd--$OPTARG"
	PGPWD=$OPTARG;
        ;;
        s)
        echo "OPT--$OPTARG"
	OPTSTATUS=$OPTARG;

		read -r -p "Are You Sure? [Y/n] " input
				case $input in
				[yY][eE][sS]|[yY])
						echo $input
						;;
				[nN][oO]|[nN])
						exit 1
				;;
				*)
				echo "Invalid input..."
				exit 1
				;;
				esac
        ;;
        ?)
        echo "---$opt"
        exit 1;;
    esac
done
echo "PGNAME:"$PGNAME
echo "SERVERVERSION:"$SERVERVERSION
echo "PGIP:"$PGIP
echo "PGPORT:"$PGPORT
echo "PGUSER:"$PGUSER
echo "PGPWD:"$PGPWD


################################## INSTALL FUN ####################################################
##//判断安装包文件是否存在 参数一个要解压的文件名
function unzipInstallPackage(){
   ##echo $PGNAME.zip
    if [ ! -e "$PGNAME.zip" ] ;
    then
         return 0
    else
        ##//存在则赋权并解压
        chmod 755 $PGNAME.zip
        unzip -o $PGNAME.zip
	sleep 2
        echo "Progress Unzip File Complete 20%"
        return 1
    fi
}

##//判断服务端口是否被占用 参数一个 要检测的端口
function serverPortStatus(){
    netstat -lnut | grep $SERVERPORT
    if [ "$?" == 0 ];
    then
        return 0
    else
        return 1
    fi
}

##//在usr目录下创建“CommandCenter”目录
function createCommandCenterDir(){
    if [ ! -d $HOMEPATH ];
    then
        mkdir $HOMEPATH
    fi
    if [ ! -d $HOMEPATH/$SERVERNAME ];
    then
	mkdir $HOMEPATH/$SERVERNAME
    fi
        return 0
}

 ##//在“CommandCenter”目录下创建服务目录 入参一个要在CommandCenter 下创建的目录
function createServerDir(){
    if [ ! -d $HOMEPATH/$SERVERNAME/$1 ];
    then
        mkdir $HOMEPATH/$SERVERNAME/$1
    fi
        return 0
}

##//赋权并解压应用到tomcat/webapps目录下 两个参数 第一个是要挤压的文件 第二个是要移入的目录
function installServer(){
  ##echo $1
  ##echo $2
    chmod 755 $1
    unzip -o -q $1 -d $2
}



##//循环添加端口到防火墙规则
function openFirewallPort(){
#循环添加端口到防火墙规则中
FIREWALLSTATE=$(firewall-cmd --state)
FIREWALLOPEN="running"
echo "FIREWALLSTATE" $FIREWALLSTATE
if [ "$FIREWALLSTATE" = "$FIREWALLOPEN" ];
then
    echo "FIREWALL is OPENED"
else
    echo "OPENED FIREWALL"
    systemctl start firewalld
fi

for i in $OPENPORT
do
    echo "Adding $i Port to firewall"
    firewall-cmd --add-port=${i}/tcp
done
#将以上设置的临时防火墙规则,转换为永久有效的规则(确保重启后有效)
firewall-cmd --runtime-to-permanent
firewall-cmd --reload

if [ "$FIREWALLSTATE" = "$FIREWALLOPEN" ];
then
    echo "FIREWALL is OPENED"
else
    echo "CLOSED FIREWALL"
    systemctl stop firewalld
fi

}

##//添加防火墙端口
function addPortToFirewalld() {
  FIREWALLSTATE=$(firewall-cmd --state -q && echo "true" || echo "false")
  if [ "$FIREWALLSTATE" = "true" ];
  then
      echo "Firewall is runnging ,Prepare to Add Port to firewall"
  else
      echo "Firewall is not running, Prepare to Staring Firewall"
      systemctl start firewalld
  fi

  for i in $OPENPORT
  do
    echo "Adding ${i} Port to firewall"
    firewall-cmd --permanent --zone=public --add-port=${i}/tcp -q
  done
  firewall-cmd --reload

      if [ "$FIREWALLSTATE" = "true" ];
  then
       echo "Firewall is runnging"
  else
       echo "Close Firewall"
       systemctl stop firewalld
  fi
}

##//移除防火墙端口
function removePortToFirewalld(){
  FIREWALLSTATE=$(firewall-cmd --state -q && echo "true" || echo "false")
  if [ "$FIREWALLSTATE" = "true" ];
  then
       echo "Firewall is runnging ,Prepare to Remove Port to firewall"
  else
       echo "Firewall is not running, Prepare to Staring Firewall"
       systemctl start firewalld
  fi

  for i in $OPENPORT
  do
   echo "Removing ${i} Port to firewall"
   firewall-cmd --permanent --zone=public --remove-port=${i}/tcp -q
  done
  firewall-cmd --reload

    if [ "$FIREWALLSTATE" = "true" ];
  then
       echo "Firewall is runnging"
  else
       echo "Close Firewall"
       systemctl stop firewalld
  fi
}


########################################## UNINSTALL FUN ############################################

##//删除服务 入参一个 服务所有文件目录名
function deleteServer(){
    rm -rf $HOMEPATH/$SERVERNAME
    sleep 2
    echo "Progress CDSS Uninstalled 80%"
 }

##//删除CommandCenter目录
function deleteHomePath(){
    if [ "'ls -A ${HOMEPATH}'" = "" ];
    then
        rm -rf $HOMEPATH
	sleep 2
        echo "Progress JDK Uninstalled 90%"
    fi
}
##//dockerRun命令
function dockerRun(){
	docker run -d --network host --log-opt max-size=500m --restart=always \
	-v $HOMEPATH/$SERVERNAME/server/logs:/usr/CommandCenter/tomcat/logs \
	-v $HOMEPATH/$SERVERNAME/server/ucmslogs:/usr/CommandCenter/tomcat/bin/logs/ucms \
	-v $HOMEPATH/$SERVERNAME/server/conf/ucms.db:/usr/CommandCenter/tomcat/webapps/ucms/WEB-INF/classes/static/sqllite/ucms.db \
	-v $HOMEPATH/$SERVERNAME/server/conf/application-dev.yml:/usr/CommandCenter/tomcat/webapps/ucms/WEB-INF/classes/application-dev.yml \
	-v /usr/CommandCenter/icc:/usr/CommandCenter/icc \
	-v /usr/CommandCenter/dss:/usr/CommandCenter/dss \
	-v /usr/CommandCenter/CDSS:/usr/CommandCenter/CDSS \
	-v /usr/CommandCenter/SMP:/usr/CommandCenter/SMP \
	-v /usr/CommandCenter/VCS:/usr/CommandCenter/VCS \
	-v /usr/CommandCenter/CAD:/usr/CommandCenter/CAD \
	-v /usr/CommandCenter/IPCS:/usr/CommandCenter/IPCS \
	-v /usr/CommandCenter/AIA:/usr/CommandCenter/AIA \
	-v /usr/CommandCenter/MPA:/usr/CommandCenter/MPA \
	-v /usr/CommandCenter/SMT:/usr/CommandCenter/SMT \
	-v /usr/CommandCenter/activemq:/usr/CommandCenter/activemq \
	-v /usr/CommandCenter/redis:/usr/CommandCenter/redis \
	-v /usr/CommandCenter/SSOP:/usr/CommandCenter/SSOP \
	-v /usr/CommandCenter/WEBICC:/usr/CommandCenter/WEBICC \
	-v /usr/CommandCenter/puctomq:/usr/CommandCenter/puctomq \
	--name=$CONTAINERNAME $DOCKERNAME:$SERVERVERSION
}
##//dockerRun命令
function dockerStop(){
  docker stop $CONTAINERNAME
}
##//dockerRun命令
function dockerStart(){
  docker start $CONTAINERNAME
}
##//dockerRun命令
function dockerRm(){
  docker rm -f $CONTAINERNAME
  docker rmi --force `docker images | grep $DOCKERNAME | awk '{print $3}'`
}
##//dockerRun命令
function dockerLoad(){
  dockerRm
  docker load -i cdss_server.tar
}
########################################## MAIN FUN ############################################
##//判断是安装还是卸载 1 安装  0卸载
if [ "$OPTSTATUS" == '1' ];
then
##//判断是否输入版本信息
    if [  -z $SERVERVERSION ];
    then
	if [ -f version ];then
		while read -r line  #&& [ ! -z SERVERVERSION ]
		do
			SERVERVERSION=$line
			echo "readfile Version:$SERVERVERSION"
		done <version
	else
		echo "version is empty,please input it"
		exit 0
	fi
    else
	echo "input Version:$SERVERVERSION"
    fi
##//开放(关闭)防火墙策略
addPortToFirewalld
##//加载docker镜像
dockerLoad
##//判断22401端口是否被占用
serverPortStatus
   if [ "$?" == 0 ];
   then
       echo "Error $SERVERPORT port is occupied! Finished"
   else
       ##//创建CommandCenter目录
       createCommandCenterDir
       ##//创建server目录
       createServerDir "server"
       ##//创建server/logs目录
	   createServerDir "server/logs"
       createServerDir "server/ucmslogs"
       ##//创建server/conf目录
       createServerDir "server/conf"
       cp -r configfile $HOMEPATH/$SERVERNAME/server/conf/
	   cp -r ucms.db $HOMEPATH/$SERVERNAME/server/conf/
	   cp -r application-dev.yml $HOMEPATH/$SERVERNAME/server/conf/
	   cp -r appsettings.json $HOMEPATH/$SERVERNAME/server/conf/
################################ Medical ##################################
       sleep 2
       echo "Progress CDSS Installed 70%"


################################# docker run #################################
       ##//启动docker容器
       dockerRun
       echo "Progress CDSS Installed 100%"
   fi

##//如果用户输入0的情况下执行卸载程序
elif [ "$OPTSTATUS" == '0' ];
then

  ##//停掉docker容器
  dockerRm

  ##//删除服务
  deleteServer

  ##//删除CommandCenter目录
  deleteHomePath
  sleep 2
  echo "Progress Uninstall Finished 100%"
##//如果用户输入2的情况下停止docker容器
elif [ "$OPTSTATUS" == '2' ];
then
  ##//停掉docker容器
  dockerStop
  echo "docker stoped"
##//如果用户输入3的情况下启动docker容器
elif [ "$OPTSTATUS" == '3' ];
then
  ##//启动docker容器
  dockerStart
  echo "docker running"
##//如果用户输入的不是0,1,2,3则执行这里
else
  echo "You can only enter 0/1/2/3."
fi
